//
//  LuYinListController.swift
//  JianTingSwift
//
//  Created by zhibao on 2024/7/11.
//

import UIKit

class LuYinListController: SuperController,UITableViewDelegate,UITableViewDataSource,DataChangeDelegate,UIDocumentInteractionControllerDelegate,TZImagePickerControllerDelegate{
    var docum = "luyin"
    var navTitle = "录音列表"
    fileprivate var dataArray = [String]()
    fileprivate var showTableView:MYTableView!
    fileprivate var document:UIDocumentInteractionController!
    fileprivate var yulanPath = ""
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.getListData()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.gk_interactivePopDisabled = true
        self.gk_navTitle = navTitle
        self.initTableView()
        
        let shuoBtn = UIButton(type: .custom)
        shuoBtn.frame = CGRect(x: 0, y: 0, width: 60, height: 40)
        shuoBtn.tag = 101
        shuoBtn.tintColor = UIColor.white
        shuoBtn.titleLabel?.font = MY_SCALE_BoldFont(12)
        shuoBtn.setTitleColor(UIColor.white, for: .normal)
        shuoBtn.setImage(UIImage(systemName: "plus"), for: .normal)
        shuoBtn.addTarget(self, action: #selector(addClick), for: .touchUpInside)
        let item = UIBarButtonItem(customView: shuoBtn)
        self.gk_navRightBarButtonItem = item
    }
    
    func initTableView() {
        showTableView = MYTableView(frame: CGRectMake(0, navigationFullHeight(), SCREEN_WIDTH, SCREEN_HEIGHT - navigationFullHeight()), style: .plain)
        showTableView.delegate = self
        showTableView.dataSource = self
        showTableView.dataChangeDelegate = self
        showTableView.separatorStyle = .none
        showTableView.register(RecordLCell.self, forCellReuseIdentifier: "RecordLCell")
        self.view.addSubview(showTableView)
        showTableView.noDataType = .TableViewNoDataType_FILE
        showTableView.mj_footer?.endRefreshingWithNoMoreData()
        
        let btn = UIButton(type: .custom)
        btn.setImage(UIImage(systemName: "waveform"), for: .normal)
        btn.tintColor = .white
        btn.backgroundColor = MYColor.color(withHexString: "ff8070", alpha: 1)
        btn.setTitle("录音", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.layer.cornerRadius = pixw(p: 35)
        btn.titleLabel?.font = MY_SCALE_BoldFont(15)
        btn.addGestureRecognizer(UITapGestureRecognizer(actionBlock: { sender in
            if  UserInfoManager.shared().isLogin == false {
                YJLoginHelper.login(with: self)
                return
            }
            
            if UserInfoManager.shared().isVip() == false {
                Helper.alertShow(withTitle: LocalizedString("提示"), withContent: LocalizedString("您不是VIP会员，暂时无法使用该功能！点击去开通解锁该功能！"), withSureBtnTitle: LocalizedString("去开通"), withCancelBtnTitle: LocalizedString("取消")) { index in
                    //去往购买中心
                    if index == 1 {
                        let controller = PayMarkController()
                        self.navigationController?.pushViewController(controller, animated: true)
                    }
                }
                return
            }
            let controller = LuYingZhongController()
            controller.docum = self.docum
            self.navigationController?.pushViewController(controller, animated: true)
        }))
        self.view.addSubview(btn)
        btn.snp.makeConstraints { make in
            make.right.equalTo(self.view).offset(pixw(p:-20))
            make.width.height.equalTo(pixw(p:70))
            make.bottom.equalTo(-safeDistanceBottom() - pixw(p:80))
        }
    }
    
    func getListData(){
        let tempData = try? Helper.contentsOfDirectory(atPath: docum)
        if tempData != nil {
            dataArray = tempData!
            DLog(message: "dataArray === \(dataArray)")
            self.showTableView.reloadData()
        }
    }
    
    @objc func addClick() {
        Helper.alertShow(withTitle: LocalizedString("新建"), withSureBtnTitle: LocalizedString("确定"), withCancelBtnTitle: LocalizedString("取消")) { anwer in
            if (anwer ?? "").qmui_trimAllWhiteSpace.count > 0 {
                Helper.createDir(Helper.getPath()! + "/" + self.docum + "/" + (anwer ?? "").qmui_trimAllWhiteSpace)
                QMUITips.showSucceed(LocalizedString("创建成功！"))
                self.getListData()
            }
        }
    }
}

extension LuYinListController {
    func refreshData(withTabelViewTag tableViewTag: Int) {
        self.getListData()
    }
    
    func loadMoreData(withTabelViewTag tableViewTag: Int) {
        self.getListData()
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let nameUrl = dataArray[indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: "RecordLCell") as! RecordLCell
        cell.updata(name: nameUrl,docum: self.docum, type: 1)
        cell.doneBlock = {
            if  UserInfoManager.shared().isLogin == false {
                YJLoginHelper.login(with: self)
                return
            }
            
            if UserInfoManager.shared().isVip() == false {
                Helper.alertShow(withTitle: LocalizedString("提示"), withContent: LocalizedString("您不是VIP会员，暂时无法使用该功能！点击去开通解锁该功能！"), withSureBtnTitle: LocalizedString("去开通"), withCancelBtnTitle: LocalizedString("取消")) { index in
                    //去往购买中心
                    if index == 1 {
                        let controller = PayMarkController()
                        self.navigationController?.pushViewController(controller, animated: true)
                    }
                }
                return
            }
            //分享
            let lastUrl = self.docum +  "/" + nameUrl
            let path = Helper.getPath()! + "/" + lastUrl
            self.showTableView.reloadData()
            self.shareFile(path: path, lastUrl: lastUrl)
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let name = dataArray[indexPath.row]
        let nameArray = name.components(separatedBy: ".")
        if nameArray.count < 2 {
            let subController = JianTingSwift.LuYinListController()
            subController.docum = "\(self.docum)/\(name)"
            subController.navTitle = name
            self.navigationController?.pushViewController(subController, animated: true)
        }else{
            let lastUrl = self.docum +  "/" + name
            let path = Helper.getPath()! + "/" + lastUrl
            self.document = UIDocumentInteractionController(url: URL(filePath: path))
            self.document.delegate = self
            let canOpen = self.document.presentPreview(animated: true)
            if canOpen == false {
                DLog(message: "预览失败")
            }
        }
        
    }
    
    func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        
        let name = dataArray[indexPath.row]
        let nameArray = name.components(separatedBy: ".")
        let reNameAction = UIContextualAction(style: .normal, title: LocalizedString("重命名")) { (action, view, completed)  -> Void in
            if  UserInfoManager.shared().isLogin == false {
                YJLoginHelper.login(with: self)
                return
            }
            
            if UserInfoManager.shared().isVip() == false {
                Helper.alertShow(withTitle: LocalizedString("提示"), withContent: LocalizedString("您不是VIP会员，暂时无法使用该功能！点击去开通解锁该功能！"), withSureBtnTitle: LocalizedString("去开通"), withCancelBtnTitle: LocalizedString("取消")) { index in
                    //去往购买中心
                    if index == 1 {
                        let controller = PayMarkController()
                        self.navigationController?.pushViewController(controller, animated: true)
                    }
                }
                return
            }
            Helper.alertShow(withTitle: LocalizedString("重命名"), withSureBtnTitle: LocalizedString("确定"), withCancelBtnTitle: LocalizedString("取消")) { newName in
                if (newName!.qmui_trimAllWhiteSpace.count > 0){
                    for temName in self.dataArray {
                        let temNameArray = temName.components(separatedBy: ".")
                        if temNameArray.first == newName!.qmui_trimAllWhiteSpace {
                            QMUITips.showError(LocalizedString("提示"), detailText: LocalizedString("名称重复"))
                            return
                        }
                    }
                    Helper.rename(withUrl: name, withNewName: newName!.qmui_trimAllWhiteSpace , withDocum: self.docum, withType: DOCUMENTYPE)
                    QMUITips.showSucceed("重命名成功！")
                    self.getListData()
                }
            }
        }
        reNameAction.backgroundColor = MYColor.color(withHexString: "#1AB8A6")
        
        let deleteAction = UIContextualAction(style: .normal, title: LocalizedString("删除")) { (action, view, completed)  -> Void in
            if  UserInfoManager.shared().isLogin == false {
                YJLoginHelper.login(with: self)
                return
            }
            
            if UserInfoManager.shared().isVip() == false {
                Helper.alertShow(withTitle: LocalizedString("提示"), withContent: LocalizedString("您不是VIP会员，暂时无法使用该功能！点击去开通解锁该功能！"), withSureBtnTitle: LocalizedString("去开通"), withCancelBtnTitle: LocalizedString("取消")) { index in
                    //去往购买中心
                    if index == 1 {
                        let controller = PayMarkController()
                        self.navigationController?.pushViewController(controller, animated: true)
                    }
                }
                return
            }
            Helper.alertShow(withTitle: LocalizedString("是否删除？"), withContent: "", withSureBtnTitle: LocalizedString("确定"), withCancelBtnTitle: LocalizedString("取消")) { selectIndex in
                if(selectIndex == 1){
                    let lastUrl = "\(self.docum)/\(name)"
                    let path = Helper.getPath()! + "/" + lastUrl
                    try? FileManager.default.removeItem(atPath: path)
                    QMUITips.showSucceed("删除成功！")
                }
                self.getListData()
            }
        }
        deleteAction.backgroundColor = MYColor.color(withHexString: "#FC2F55")
        
        let shareAction = UIContextualAction(style: .normal, title: LocalizedString("分享")) { (action, view, completed)  -> Void in
            if  UserInfoManager.shared().isLogin == false {
                YJLoginHelper.login(with: self)
                return
            }
            
            if UserInfoManager.shared().isVip() == false {
                Helper.alertShow(withTitle: LocalizedString("提示"), withContent: LocalizedString("您不是VIP会员，暂时无法使用该功能！点击去开通解锁该功能！"), withSureBtnTitle: LocalizedString("去开通"), withCancelBtnTitle: LocalizedString("取消")) { index in
                    //去往购买中心
                    if index == 1 {
                        let controller = PayMarkController()
                        self.navigationController?.pushViewController(controller, animated: true)
                    }
                }
                return
            }
            //分享
            let lastUrl = self.docum +  "/" + name
            let path = Helper.getPath()! + "/" + lastUrl
            self.showTableView.reloadData()
            self.shareFile(path: path, lastUrl: lastUrl)
        }
        shareAction.backgroundColor = MYBlue
        
        var config = UISwipeActionsConfiguration(actions: [deleteAction,reNameAction,shareAction])
        if nameArray.count < 2 {
            config = UISwipeActionsConfiguration(actions: [deleteAction,reNameAction])
        }
        config.performsFirstActionWithFullSwipe = false
        return config
    }
    
    fileprivate func shareFile(path:String,lastUrl:String){
        self.showTableView.reloadData()
        document = UIDocumentInteractionController(url:URL(fileURLWithPath: path))
        document.delegate = self
        let _ = self.document.presentOptionsMenu(from: self.view.bounds, in: self.view, animated: true)
    }
}

extension LuYinListController{
    func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
        return self
    }
    
    func documentInteractionControllerViewForPreview(_ controller: UIDocumentInteractionController) -> UIView? {
        return self.view
    }
    
    func documentInteractionControllerRectForPreview(_ controller: UIDocumentInteractionController) -> CGRect {
        return self.view.frame
    }
    
    func documentInteractionControllerDidDismissOpenInMenu(_ controller: UIDocumentInteractionController) {
        DLog(message: "disMiss")
    }
}
